package com.time.company.components.compose;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BaseLvAdapter;
import com.time.company.base.BasePW;
import com.time.company.components.popup.ChoosePW;
import com.time.company.components.popup.ExitEditPW;
import com.time.company.components.popup.DatePW;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.compose.ActPeriod;
import com.time.company.servermodel.compose.ApplyInfo;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.TimeUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.utils.string.Constant;
import com.time.company.views.WrapHeightListView;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.ComposeParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 申请志愿
 * Created by Bing on 2017/11/15.
 * E-mail is tx16bing@163.com
 */

public class ApplyActivity extends BaseActivity implements View.OnClickListener, AMapLocationListener {

    // Permission
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 102;
    private static final int DENIED_PERMISSION_REQUEST_CODE = 103;
    private static final int TIME_MAP_REQUEST_CODE = 11;

    // 窗口背景属性
    private WindowManager.LayoutParams attributes;
    private ExitEditPW exitEditPW;
    private ChoosePW choosePW;
    private DatePW datePW;

    private RelativeLayout rlParent;
    private TextView tvTimeTotalHour, tvTimeTotalMin, tvTimeTotalSecond, tvTimeCoin, tvApplyType, tvLocation, tvCommit;
    private EditText etApplyNum;
    private ImageView ivClose;

    private ImageView ivMin, ivAdd;
    private TextView tvPeriod;
    private WrapHeightListView lvPeriod;
    private List<ActPeriod> curPeriods = new ArrayList<>();
    private PeriodAdapter mAdapter;

    // Location
    private AMapLocationClient locationRequest;
    private double mLatitude, mLongitude;
    private String curCity, curLocation;

    private Request request;
    private static final int GET_TIME_ASSET_WHAT = 30;
    private static final int GET_SERVICE_TYPE_LIST_WHAT = 31;
    private static final int APPLY_COMPANY_ACTIVITY_WHAT = 32;
    // 公益类型
    private List<String> mServiceTypes = new ArrayList<>();

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, ApplyActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply);
        assignViews();
        bindListener();
        andPermission();
        timeAssetRequest();
        serviceTypeRequest();
        bindPeriod();
    }

    private void assignViews() {
        rlParent = findView(R.id.rl_apply_parent);
        tvTimeTotalHour = findView(R.id.tv_apply_time_total_hour);
        tvTimeTotalMin = findView(R.id.tv_apply_time_total_minute);
        tvTimeTotalSecond = findView(R.id.tv_apply_time_total_second);
        tvTimeCoin = findView(R.id.tv_apply_time_coin);
        tvApplyType = findView(R.id.tv_apply_type);
        tvLocation = findView(R.id.tv_apply_location);
        tvCommit = findView(R.id.tv_apply_commit);
        etApplyNum = findView(R.id.et_apply_num);
        ivClose = findView(R.id.iv_apply_close);
        ivMin = findView(R.id.iv_apply_min);
        ivAdd = findView(R.id.iv_apply_add);
        tvPeriod = findView(R.id.tv_apply_period);
        lvPeriod = findView(R.id.lv_apply_period);
    }

    private void bindListener() {
        tvApplyType.setOnClickListener(this);
        tvLocation.setOnClickListener(this);
        tvCommit.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        ivMin.setOnClickListener(this);
        ivAdd.setOnClickListener(this);
    }

    private void bindPeriod() {
        String periodNum = tvPeriod.getText().toString().trim();
        if (TextUtils.isEmpty(periodNum)) {
            return;
        }

        int num = Integer.parseInt(periodNum);
        for (int i = 0; i < num; i++) {
            curPeriods.add(new ActPeriod());
        }

        setAdapter();

    }

    private void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new PeriodAdapter(this, curPeriods);
            mAdapter.setOnViewClickListener(new BaseLvAdapter.OnViewClickListener<ActPeriod>() {
                @Override
                public void onViewClick(View view, int position, ActPeriod o, int type) {
                    if (type == 10) {
                        // start
                        if (datePW == null || !datePW.isShowing()) {
                            launchDate(position, DatePW.START_TIME);
                        } else {
                            return;
                        }
                    } else if (type == 11) {
                        // end
                        if (datePW == null || !datePW.isShowing()) {
                            launchDate(position, DatePW.END_TIME);
                        } else {
                            return;
                        }
                    } else {
                        return;
                    }
                }
            });
            lvPeriod.setAdapter(mAdapter);
        } else {
            mAdapter.updateData(curPeriods);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_apply_type:
                if (choosePW == null || !choosePW.isShowing()) {
                    launchChoose(resources.getInteger(R.integer.pw_type_service_type),
                            this.mServiceTypes, tvApplyType.getText().toString());
                } else {
                    return;
                }
                break;

            case R.id.tv_apply_location:
                TimeMapActivity.start(this, TIME_MAP_REQUEST_CODE,
                        getString(R.string.map_flag_apply),
                        tvLocation.getText().toString());
                break;

            case R.id.iv_apply_min:
                String periodMin = tvPeriod.getText().toString();
                if (!TextUtils.isEmpty(periodMin)) {
                    int i = Integer.parseInt(periodMin);
                    i--;
                    tvPeriod.setText(i + "");
                    if (i < 1) {
                        tvPeriod.setText("1");
                        return;
                    }
                    curPeriods.remove(curPeriods.size() - 1);
                    setAdapter();
                }
                break;

            case R.id.iv_apply_add:
                String periodAdd = tvPeriod.getText().toString();
                if (!TextUtils.isEmpty(periodAdd)) {
                    int i = Integer.parseInt(periodAdd);
                    i++;
                    tvPeriod.setText(i + "");
                    curPeriods.add(new ActPeriod());
                    setAdapter();
                }
                break;

            case R.id.tv_apply_commit:
                if (checkForm()) {
                    commitApply();
                }
                break;

            case R.id.iv_apply_close:
                launchExit();
//                if (checkExit()) {
//                    launchExit();
//                } else {
//                    finish();
//                }
                break;

            default:
                break;

        }
    }

    /**
     * 获取时间资产
     */
    private void timeAssetRequest() {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            ComposeParameters parameters = new ComposeParameters();
            parameters.setCommand(application.getString(R.string.command_getTimeAssert));
            parameters.setUserId(application.getAccount());
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    GET_TIME_ASSET_WHAT, false, true, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    /**
     * 获取公益类型列表
     */
    private void serviceTypeRequest() {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            ComposeParameters parameters = new ComposeParameters();
            parameters.setCommand(application.getString(R.string.command_getServiceTypeList));
            parameters.setUserId(application.getAccount());
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    GET_SERVICE_TYPE_LIST_WHAT, true, true, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    /**
     * 申请志愿
     */
    private void commitApply() {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            ComposeParameters parameters = new ComposeParameters();
            parameters.setCommand(application.getString(R.string.command_applyCompanyActivities));
            parameters.setUserId(application.getAccount());
            parameters.setType(tvApplyType.getText().toString());
            parameters.setCollectNum(etApplyNum.getText().toString().trim());
            parameters.setLocation(curLocation);
            parameters.setLatitude(mLatitude + "");
            parameters.setLongitude(mLongitude + "");
            parameters.setCity(curCity);
            List<ComposeParameters.Periods> periodses = new ArrayList<>();
            for (ActPeriod actPeriod : curPeriods) {
                ComposeParameters.Periods periods = new ComposeParameters.Periods();
                periods.setStartTime(actPeriod.getStart());
                periods.setEndTime(actPeriod.getEnd());
                periodses.add(periods);
            }
            parameters.setPeriods(periodses);
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    APPLY_COMPANY_ACTIVITY_WHAT, true, true, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    private boolean checkForm() {
        if (TextUtils.isEmpty(tvApplyType.getText().toString())) {
            ToastUtils.showShort("请选择需要举办的公益类型");
            return false;
        } else if (TextUtils.isEmpty(etApplyNum.getText().toString())) {
            ToastUtils.showShort("请输入征集的人数");
            return false;
        } else if (TextUtils.isEmpty(tvLocation.getText().toString())) {
            ToastUtils.showShort("请选择你的活动地点");
            return false;
        }

        for (ActPeriod period : curPeriods) {
            if (TextUtils.isEmpty(period.getStart().toString())) {
                ToastUtils.showShort("请选择你的开始时间");
                return false;
            } else if (TextUtils.isEmpty(period.getEnd().toString())) {
                ToastUtils.showShort("请选择你的结束时间");
                return false;
            }
        }

        return true;
    }

    private boolean checkExit() {
        if (!TextUtils.isEmpty(tvApplyType.getText().toString())) {
            return true;
        } else if (!TextUtils.isEmpty(etApplyNum.getText().toString())) {
            return true;
        } /*else if (!TextUtils.isEmpty(tvLocation.getText().toString())) {
            return true;
        } */

        for (ActPeriod period : curPeriods) {
            if (!TextUtils.isEmpty(period.getStart())) {
                return true;
            } else if (!TextUtils.isEmpty(period.getEnd())) {
                return true;
            }
        }

        return false;
    }

    private void launchExit() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        exitEditPW = new ExitEditPW(this, rlParent);
        exitEditPW.setTip("请问确定放弃此次输入吗？");
        exitEditPW.setLeft(getString(R.string.btn_think_about));
        exitEditPW.setRight(getString(R.string.btn_confirm));
        exitEditPW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String result) {
                finish();
            }
        });
        exitEditPW.showAtLocation(rlParent, Gravity.CENTER, 0, 0);
        exitEditPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void launchChoose(int mType, List<String> data, String choose) {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        choosePW = new ChoosePW(this, rlParent, data, mType, choose);
        choosePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(final int type, String result) {
                if (type == resources.getInteger(R.integer.pw_type_service_type)) {
                    tvApplyType.setText(result);
                }
            }
        });
        choosePW.showAtLocation(rlParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        choosePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void launchDate(final int position, int type) {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        datePW = new DatePW(this, df.format(date), type);
        datePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(int type, String result) {
                ActPeriod period = curPeriods.get(position);
                if (type == DatePW.START_TIME) {
                    period.setStart(result);
                } else {
                    period.setEnd(result);
                }
                setAdapter();
            }
        });
        datePW.showAtLocation(rlParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        datePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void andPermission() {
        // 需要调用AndPermission来开启定位权限提示
        AndPermission.with(this)
                .requestCode(LOCATION_PERMISSION_REQUEST_CODE)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(ApplyActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
                // 表示定位的权限申请通过
//                createLocationRequest();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权
            if (AndPermission.hasAlwaysDeniedPermission(ApplyActivity.this, deniedPermissions)) {
//                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(ApplyActivity.this, DENIED_PERMISSION_REQUEST_CODE).show();
//
            }
        }
    };

    protected void createLocationRequest() {

        tvLocation.setText("定位中...");

        // 初始化请求
        locationRequest = new AMapLocationClient(getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(this);

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);

        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);

        mLocationOption.setOnceLocation(true);

        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);

        locationRequest.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            Logger.e("Amap location Error");
            ToastUtils.showShort("定位失败");
            return;
        }

        Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                " and lon : " + aMapLocation.getLongitude());
        mLatitude = aMapLocation.getLatitude();
        mLongitude = aMapLocation.getLongitude();
        curCity = aMapLocation.getCity();
        curLocation = aMapLocation.getAddress();
        tvLocation.setText(aMapLocation.getAddress() + "");
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            if (what == GET_TIME_ASSET_WHAT) {
                // 时间资产
                ApplyInfo applyInfo = basicBean.parseData(ApplyInfo.class);
                if (applyInfo == null) return;

                tvTimeCoin.setText(applyInfo.getServiceTime().getTimeCoinAsset());
                String timeServiceAsset = applyInfo.getServiceTime().getTimeServiceAsset();

                if (!TextUtils.isEmpty(timeServiceAsset)
                        && !TextUtils.equals(timeServiceAsset, application.getString(R.string.zero))) {
                    long distanceTimes = Long.parseLong(timeServiceAsset);
                    int[] format = TimeUtils.formatTimeArray(distanceTimes);
                    if (format.length > 2) {
                        // 00:00:00
                        if (String.valueOf(format[0]).length() == 1) {
                            tvTimeTotalHour.setText(new StringBuffer().append("0").append(format[0]).append(""));
                        } else {
                            tvTimeTotalHour.setText(new StringBuffer().append(format[0]).append(""));
                        }

                        if (String.valueOf(format[1]).length() == 1) {
                            tvTimeTotalMin.setText(new StringBuffer().append("0").append(format[1]).append(""));
                        } else {
                            tvTimeTotalMin.setText(new StringBuffer().append(format[1]).append(""));
                        }
                        if (String.valueOf(format[2]).length() == 1) {
                            tvTimeTotalSecond.setText(new StringBuffer().append("0").append(format[2]).append(""));
                        } else {
                            tvTimeTotalSecond.setText(new StringBuffer().append(format[2]).append(""));
                        }
                    } else if (format.length > 1) {
                        tvTimeTotalHour.setText(getString(R.string.double_zero));

                        if (String.valueOf(format[0]).length() == 1) {
                            tvTimeTotalMin.setText(new StringBuffer().append("0").append(format[0]).append(""));
                        } else {
                            tvTimeTotalMin.setText(new StringBuffer().append(format[0]).append(""));
                        }
                        if (String.valueOf(format[1]).length() == 1) {
                            tvTimeTotalSecond.setText(new StringBuffer().append("0").append(format[1]).append(""));
                        } else {
                            tvTimeTotalSecond.setText(new StringBuffer().append(format[1]).append(""));
                        }
                    } else {
                        tvTimeTotalHour.setText(getString(R.string.double_zero));
                        tvTimeTotalMin.setText(getString(R.string.double_zero));
                        tvTimeTotalSecond.setText(getString(R.string.double_zero));
                    }
                } else {
                    tvTimeTotalHour.setText(getString(R.string.double_zero));
                    tvTimeTotalMin.setText(getString(R.string.double_zero));
                    tvTimeTotalSecond.setText(getString(R.string.double_zero));
                }

            } else if (what == GET_SERVICE_TYPE_LIST_WHAT) {
                // 类型列表
                ApplyInfo applyInfo = basicBean.parseData(ApplyInfo.class);
                if (applyInfo == null) return;
                List<ApplyInfo.ServiceType> serviceTypes = applyInfo.getServiceTypes();
                if (null != serviceTypes) {
                    for (ApplyInfo.ServiceType serviceType : serviceTypes) {
                        this.mServiceTypes.add(serviceType.getServiceType());
                    }
                }
            } else if (what == APPLY_COMPANY_ACTIVITY_WHAT) {
                ApplyScActivity.start(this);
                finish();
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case DENIED_PERMISSION_REQUEST_CODE:
                // 用户从设置中回来，无论有没有开启所需要的权限
//                ToastUtils.showShort("从设置中回来");
                break;

            case TIME_MAP_REQUEST_CODE:
                if (null != data) {
                    mLatitude = data.getDoubleExtra(Constant.LATITUDE, 0.0d);
                    mLongitude = data.getDoubleExtra(Constant.LONGITUDE, 0.0d);
                    curCity = data.getStringExtra(Constant.CITY);
                    curLocation = data.getStringExtra(Constant.LOCATION);

                    if (!TextUtils.isEmpty(curLocation)) {
                        tvLocation.setText(curLocation);
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        launchExit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != locationRequest) {
            locationRequest.stopLocation();
        }

        if (null != exitEditPW) {
            exitEditPW.dismiss();
            exitEditPW = null;
        }

        if (null != choosePW) {
            choosePW.dismiss();
            choosePW = null;
        }
    }

    class PeriodAdapter extends BaseLvAdapter<ActPeriod> {

        public PeriodAdapter(Context context, List<ActPeriod> list) {
            super(context, list);
        }

        @Override
        public int getItemResourceId(int type) {
            return R.layout.item_apply_periods;
        }

        @Override
        public View getItemView(final int position, View convertView, ViewHolder holder, int type) {
            final ActPeriod period = (ActPeriod) getItem(position);
            TextView tvNum = holder.getView(R.id.tv_apply_period_num);
            TextView tvStart = holder.getView(R.id.tv_apply_start_time);
            TextView tvEnd = holder.getView(R.id.tv_apply_end_time);
            tvStart.setText(period.getStart());
            tvEnd.setText(period.getEnd());
            tvNum.setText(String.format(mContext.getString(R.string.apply_period_num), (position + 1) + ""));
            tvStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != onViewClickListener) {
                        onViewClickListener.onViewClick(v, position, period, 10);
                    }
                }
            });
            tvEnd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != onViewClickListener) {
                        onViewClickListener.onViewClick(v, position, period, 11);
                    }
                }
            });
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(ApplyActivity.this).inflate(getItemResourceId(type), parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            return getItemView(position, convertView, holder, type);
        }

    }
}
